const permissionService = require('../service/permission.service')
const { OPERATION_IS_PERMISSION } = require('../config/error')

// const verifyMomentPermission = async (ctx, next) => {
//   // 1 获取登录用户id/修改动态id
//   const { id } = ctx.user
//   const { momentId } = ctx.params
//   console.log(id, momentId)
//   const isPermission = await permissionService.checkMoment(momentId, id)
//   console.log(isPermission)
//   if (!isPermission) {
//     return ctx.app.emit('error', OPERATION_IS_PERMISSION, ctx)
//   }
//   await next()
// }
// const verifyPermission=function(table){
//     return async (ctx, next) => {
//           // 1 获取登录用户id/修改动态id
//           const { id } = ctx.user
//           const { momentId } = ctx.params
//           console.log(id, momentId)
//           const isPermission = await permissionService.checkMoment(momentId, id,table)
//           console.log(isPermission)
//           if (!isPermission) {
//             return ctx.app.emit('error', OPERATION_IS_PERMISSION, ctx)
//           }
//           await next()
//         }
// }
const verifyPermission = async (ctx, next) => {
  // 1 获取登录用户id/修改动态id
  const { id } = ctx.user
//   2 获取资源name/id
// name=>moment /user/coment/label
// params:{momentId:4}
//keyName=>moment
  const keyName=Object.keys(ctx.params)[0]
  const resourceId=ctx.params[keyName]
  const resourceName=keyName.replace("Id","")
  // console.log(id, resourceId,resourceName)
  const isPermission = await permissionService.checkResource(resourceId, resourceName,id)
  // console.log(isPermission)
  if (!isPermission) {
    return ctx.app.emit('error', OPERATION_IS_PERMISSION, ctx)
  }
  await next()
}

module.exports = { verifyPermission }
